package com.block.datapush.service.apipush;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.common.util.LocalDateUtil;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.Gjjutil.Base64Utils;
import com.block.datapush.service.apipush.utils.Gjjutil.RSAUtils;
import com.block.datapush.service.apipush.utils.GongjijinUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * 启飞
 */
@Service
public class QiFeiPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String queryUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("mobileMd5", mobileMd5);

        String appCode = pushApiKeyParam.getApiKey();
        String timestamp = String.valueOf(System.currentTimeMillis());

        String tranData = this.encrypt(JSON.toJSONString(bizMap), pushApiKeyParam.getApiSecret());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestNo", RandomUtil.randomString(28));
        paramMap.put("appCode", appCode);
        paramMap.put("timestamp", timestamp);
        paramMap.put("tranData", tranData);

        log.info("【启飞】撞库开始【queryUrl】{}【bizParam】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【启飞】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        String code = resultObject.getString("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code);
        pushApiResult.setCode(msg);
        pushApiResult.setResultInfo(result);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        if (StrUtil.equals(code, "200")){
            JSONObject data = resultObject.getJSONObject("data");
            Boolean existFlag = data.getBoolean("existFlag");
            if (!existFlag){
                pushApiResult.setPushSuccess(true);
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String extData = extJson.getString("itemExtData");

        String  requestUrl = pushApiKeyParam.getRegisterUrl();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("mobile", memberSourceInfo.getMobile());
        bizMap.put("username", memberSourceInfo.getRealname());
        bizMap.put("idCard", memberSourceInfo.getIdcard());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex());
        String tagInfo = memberSourceInfo.getChannelCode();
        if (StrUtil.isNotEmpty(extData)){
            tagInfo = tagInfo + "|" + extData;
        }
        bizMap.put("tagInfo", tagInfo);

        bizMap.put("province", memberSourceInfo.getProvince());
        bizMap.put("provinceCode", memberSourceInfo.getProvinceCode());

        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("cityCode", memberSourceInfo.getCityCode());

        bizMap.put("house", StrUtil.equals(memberSourceInfo.getHouse(), BaseTypeInfoEnum.House.hu001.getValue())?"hu001":"hu002");
        bizMap.put("car", StrUtil.equals(memberSourceInfo.getCar(), BaseTypeInfoEnum.Car.car001.getValue())?"car001":"car002");
        bizMap.put("gjj", StrUtil.equals(memberSourceInfo.getGjj(), BaseTypeInfoEnum.Gjj.gjj001.getValue())?"gjj001":"gjj002");
        bizMap.put("baodan", StrUtil.equals(memberSourceInfo.getBaoxian(), BaseTypeInfoEnum.Baoxian.bx001.getValue())?"bd001":"bd002");
        bizMap.put("amount", memberSourceInfo.getLoanAmount());

        String appCode = pushApiKeyParam.getApiKey();
        String timestamp = String.valueOf(System.currentTimeMillis());

        String tranData = this.encrypt(JSON.toJSONString(bizMap), pushApiKeyParam.getApiSecret());

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestNo", RandomUtil.randomString(28));
        paramMap.put("appCode", appCode);
        paramMap.put("timestamp", timestamp);
        paramMap.put("tranData", tranData);

        log.info("【启飞】导单开始【queryUrl】{}【bizParam】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String response = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【启飞】导单结束【result】{}", response);

        JSONObject resultObject = JSON.parseObject(response);
        String code = resultObject.getString("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setResultInfo(JSON.toJSONString(resultObject));
        pushApiResult.setCode(String.valueOf(code));
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));

        if (StrUtil.equals(code, "200")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
        }else{
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(false);
            pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }

    public String encrypt(String content, String aesKey) throws Exception{
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKeySpec skeySpec = new SecretKeySpec(aesKey.getBytes(StandardCharsets.UTF_8), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeBase64String(encrypted);
    }
}
